自定义内存分配器

custom-allocators.md


commit 28548db57d0acbc00ee80b43816953dbe31d53ba

分配内存并不总是最简单的事情,同时通常 Rust 默认会负责它,不过经常自定义内存分配会变得必要。编译器和标准库目前允许在编译时切换目前默认使用的全局分配器。设计目前称作RFC 1183不过这里我们会教你如何获取你自己的分配器并运行起来。

默认分配器

编译器目前自带两个默认分配器:alloc_systemalloc_jemalloc(然而一些目标平台并没有 jemalloc)。这些分配器是正常的 Rust crate 并包含分配和释放内存的 routine 的实现。标准库并不假设使用任何一个编译,而且编译器会在编译时根据被产生的输出类型决定使用哪个分配器。

编译器产生的二进制文件默认会使用alloc_jemalloc(如果可用的话)。在这种情况下编译器“控制了一切”,从它超过了最终链接的权利的角度来看。大体上这意味着分配器选择可以被交给编译器。

动态和静态库,然而,默认使用alloc_system。这里 Rust 通常是其他程序的“客人”或者处于并没有权决定应使用的分配器的世界。为此它求助于标准 API(例如,mallocfree)来获取和释放内存。

切换分配器

虽然编译器默认的选择大部分情况工作良好,也经常需要定制特定的方面。覆盖编译器关于使用哪个分配器的选择可以简单的通过链接到期望的分配器实现:

  1. #![feature(alloc_system)]
  2. extern crate alloc_system;
  3. fn main() {
  4. let a = Box::new(4); // Allocates from the system allocator.
  5. println!("{}", a);
  6. }

在这个例子中生成的二进制文件并不会默认链接到 jemalloc 而是使用了系统分配器。同理生成一个默认使用 jemalloc 的动态库可以写成:

  1. #![feature(alloc_jemalloc)]
  2. #![crate_type = "dylib"]
  3. extern crate alloc_jemalloc;
  4. pub fn foo() {
  5. let a = Box::new(4); // Allocates from jemalloc.
  6. println!("{}", a);
  7. }
  8. # fn main() {}

编写一个自定义分配器

有时甚至 jemalloc 与系统分配器之间的选择都是不够的并需要一个新的自定义的分配器。这种情况你要编写你自己实现了分配器 API(例如与alloc_systemalloc_jemallo相同)的 crate。作为一个例子,让我们看看一个简单的和声明化的alloc_system版本:

  1. # // Only needed for rustdoc --test down below.
  2. # #![feature(lang_items)]
  3. // The compiler needs to be instructed that this crate is an allocator in order
  4. // to realize that when this is linked in another allocator like jemalloc should
  5. // not be linked in.
  6. #![feature(allocator)]
  7. #![allocator]
  8. // Allocators are not allowed to depend on the standard library which in turn
  9. // requires an allocator in order to avoid circular dependencies. This crate,
  10. // however, can use all of libcore.
  11. #![no_std]
  12. // Let's give a unique name to our custom allocator:
  13. #![crate_name = "my_allocator"]
  14. #![crate_type = "rlib"]
  15. // Our system allocator will use the in-tree libc crate for FFI bindings. Note
  16. // that currently the external (crates.io) libc cannot be used because it links
  17. // to the standard library (e.g. `#![no_std]` isn't stable yet), so that's why
  18. // this specifically requires the in-tree version.
  19. #![feature(libc)]
  20. extern crate libc;
  21. // Listed below are the five allocation functions currently required by custom
  22. // allocators. Their signatures and symbol names are not currently typechecked
  23. // by the compiler, but this is a future extension and are required to match
  24. // what is found below.
  25. //
  26. // Note that the standard `malloc` and `realloc` functions do not provide a way
  27. // to communicate alignment so this implementation would need to be improved
  28. // with respect to alignment in that aspect.
  29. #[no_mangle]
  30. pub extern fn __rust_allocate(size: usize, _align: usize) -> *mut u8 {
  31. unsafe { libc::malloc(size as libc::size_t) as *mut u8 }
  32. }
  33. #[no_mangle]
  34. pub extern fn __rust_deallocate(ptr: *mut u8, _old_size: usize, _align: usize) {
  35. unsafe { libc::free(ptr as *mut libc::c_void) }
  36. }
  37. #[no_mangle]
  38. pub extern fn __rust_reallocate(ptr: *mut u8, _old_size: usize, size: usize,
  39. _align: usize) -> *mut u8 {
  40. unsafe {
  41. libc::realloc(ptr as *mut libc::c_void, size as libc::size_t) as *mut u8
  42. }
  43. }
  44. #[no_mangle]
  45. pub extern fn __rust_reallocate_inplace(_ptr: *mut u8, old_size: usize,
  46. _size: usize, _align: usize) -> usize {
  47. old_size // This api is not supported by libc.
  48. }
  49. #[no_mangle]
  50. pub extern fn __rust_usable_size(size: usize, _align: usize) -> usize {
  51. size
  52. }
  53. # // Only needed to get rustdoc to test this:
  54. # fn main() {}
  55. # #[lang = "panic_fmt"] fn panic_fmt() {}
  56. # #[lang = "eh_personality"] fn eh_personality() {}
  57. # #[lang = "eh_unwind_resume"] extern fn eh_unwind_resume() {}
  58. # #[no_mangle] pub extern fn rust_eh_register_frames () {}
  59. # #[no_mangle] pub extern fn rust_eh_unregister_frames () {}

在我们编译了这个 crate 之后,他可以被如下使用:

  1. extern crate my_allocator;
  2. fn main() {
  3. let a = Box::new(8); // Allocates memory via our custom allocator crate.
  4. println!("{}", a);
  5. }

自定义分配器的限制

使用自定义分配器时要满足一些限制,否则可能导致编译器错误:

  • 任何一个程序只能链接到一个分配器。二进制、动态库和静态库必须正好链接到一个分配器上,并且,如果没有显式选择,编译器会选择一个。另一方面,rlib 并不需要链接到一个分配器(不过仍然可以)。

  • 一个标记为#![needs_allocator](例如,目前的liballoc)的分配器使用者和一个#[allocator] crate 不能直接依赖一个需要分配器的 crate(例如,循环引用是不允许的)。这基本上意味着目前分配器必须依赖 libcore。